//暂时去掉了管理员不能建管理员的限制
var mobile="";var re_records = 0;
$(function(){
    if (sessionStorage.getItem("isgroup") == "1") {
        $("#add").hide();
    }
    $("#add").click(function(z){
        $("#user_name").attr("disabled",false);
        $("#myModal").find("span").empty();      $("#myModal").find("input").val("");
        $("#myModalLabel").text( domain.language.$t('xinzeng'));
        mobile="";
            //2操作员，3审核
            console.log("你好"+sessionStorage.getItem("roleId"))
            if(sessionStorage.getItem("roleId")=="1"){
              //  $("#jiaose option :first").hide();
                $("#jiaose").val("1");
                $("#jiaose").removeAttr("disabled");
            }if(sessionStorage.getItem("roleId")=="2"){
                $("#jiaose option :first").hide();
                $("#jiaose").val("2");
            }
            if(sessionStorage.getItem("roleId")=="3"){
                $("#jiaose option :first").hide();
                $("#jiaose").val("3");
            }
           
       
       
    });
    
    //appvm.prompt();
   // domain.jsonthis.modify();
    });
   

$(document).ready(function(){
   
  //$.fn.zTree.init($("#treeDemo"), setting, zNodes);
  domain.staticzt="456";
  domain.ajaxUrl({
  method: 'POST',
  url: domain.testUrl+"/Threeinjection/basicmManagementpage/queryRoleName",
  data: {sessionid:sessionStorage.getItem("sid")},
 // datatype:"JSON",
  success: function (response) {
      var roleArray=JSON.parse(response).lgvsRole;
      
        roleArray[0].roleName=domain.language.$t('use_js1_guanli');
        roleArray[1].roleName=domain.language.$t('use_js2_caozuo');
        roleArray[2].roleName=domain.language.$t('use_js3_shenhe');
      
    //   alert(JSON.parse(response).lgvsRole)
     $.each(roleArray, function(i, item){ 
   
            //console.log(item.roleName);

            var json="<option value='"+item.roleId+"'>"+item.roleName+"</option>";
            $("#jiaose").append(json);
                // if(sessionStorage.getItem("roleId")=="1"){
                //     $("#jiaose option:first").hide();
                   
                // }
            
     });
    
    //  that.ret=data.ret;
      //that.options=JSON.parse(lgvsRole).lgvsRole;
      


  }
});

});

$(document).ready(function () {
$.jgrid.defaults.styleUI = "Bootstrap";
$("#table_list_1").jqGrid({
    data: [],
    datatype: "local",
    height: "100%",
    recordtext:"{0} - {1}\u3000"+domain.language.$t('dev_gong')+" {2} "+domain.language.$t('dev_tiao'),
    pgtext: "{0} "+domain.language.$t('dev_gong')+" {1} "+domain.language.$t('dev_ye'),  
    emptyrecords: domain.language.$t('dev_wsjxs'),
    autowidth: true,
    shrinkToFit: true,
    rowNum: 20,
    rowList: [10, 20, 30,60,90,100,200,500],
    //colNames: ["编号", "名称", "手机号码"],
    colModel: [ {
        name: 'user_id', index: 'user_id', align:"center",width: 30, label:domain.language.$t('dev_bianhao'), align: 'center',


    },

    
    {
        name: 'user_name', index: 'user_name',align:"center", width: 30, label: domain.language.$t('dev_mingcheng'), align: 'center',


    },
    {
        name: 'coName', index: 'coName',align:"center", width: 30, label: domain.language.$t('use_danweimc'), align: 'center',
    },
    {
        name: 'roleName', index: 'roleName',align:"center", width: 30, label:  domain.language.$t('use_jiaosezn'), align: 'center',
     formatter: function (value, options, row) {
       
        
           
            if(value.trim()=="平台管理员"){
                value=domain.language.$t('use_js1_guanli');
            } if(value.trim()=="平台操作员"){
                value=domain.language.$t('use_js2_caozuo');
            }
            if(value.trim()=="平台审核员"){
                value=domain.language.$t('use_js3_shenhe');
            }
        
        return value;
    }
},
    {
        name: 'mobile', index: 'mobile',align:"center", width: 30, label: domain.language.$t('use_shoujihaoma'), align: 'center',


    },
    {
        name: 'Start_time', index: 'Start_time', align:"center",width: 30, label:  domain.language.$t('com_shijian'), align: 'center',
        formatter: function (value, options, row) {
           
           if(typeof(value)!="undefined"){
               try{
            var date = new Date(value)
               
            return date.Format("yyyy-MM-dd hh:mm:ss");
               }catch(ex){

                console.log(ex);
               }
           }
           return "";
        }

    },
    {
        name: '', index: '', width: 25,align:"center", label:  domain.language.$t('dev_caozuo'), align: 'center',
        formatter: function (value, options, row) {
         
      //console.log(options.rowId);
          var html = "<button type='button'  class='btn btn-primary' onclick=modify('"+options.rowId+"');>"+ domain.language.$t('xiugai')+"</button>";
           
            return html;
        }

    },

    
],
    pager: "#pager_list_1",
    viewrecords: true,
    multiselect: true,
    caption:  domain.language.$t('use_yonghulb'),
    hidegrid: false,
    ondblClickRow:function(row){
     

    $("#update").click();
    modify(row);
      // $('#myModal').modal('show')
  
    },
    onPaging:function(pageBtn){
        console.log(":"+pageBtn);
//	    	var re_records = $jqgrid.getGridParam('records');//获取返回的记录数
        var re_page =  $("#table_list_1").getGridParam('page');//获取返回的当前页
        var re_rowNum=  $("#table_list_1").getGridParam('rowNum');//获取每页数
        var re_total=  $("#table_list_1").getGridParam('lastpage');//获取总页数
        //alert(re_total);
        
        if(pageBtn==="next"){
           // initJqgrid(re_page+1,re_rowNum);
          // if()
           pageval=pageval+1;
           cxlist();
        }
        if(pageBtn==="prev"){
            
            pageval=pageval-1;  cxlist();
        }

        if(pageBtn=="last"){
  
            pageval=re_total;
          
            cxlist();

        }
        if(pageBtn=="first"){
  
            pageval=1;
          
            cxlist();

        }
        
        if(pageBtn=="records"){

            sizeval=$(".ui-pg-selbox").val();
            pageval=1;
            cxlist();
        }
    },

});

 $(window).resize(function(){
    $("#table_list_1").setGridWidth($(window).width());
    $("#table_list_1").setGridHeight($(window).height() - 300);

});
});
var sizeval=20;
var pageval=1;
var usernameval=$("#usnameval").val();
var conameval="";
var json="";
window.cxlist=function(){

    domain.ajaxUrl({
        method: 'POST',
        url: domain.testUrl+"/Threeinjection/basicmManagementpage/userManagementpage",
        data: {size:sizeval,page:pageval,username:$("#usnameval").val(),coid:this.sessionStorage.getItem("coid"),sessionid:sessionStorage.getItem("sid")},
       // datatype:"JSON",
        success: function (response) {
            json=response;
            var data=JSON.parse(response);
            var reader = {
                root: function (obj) { return data.rows; },
                page: function (obj) { return pageval; },
                total: function (obj) { return data.taotal; },
                records: function (obj) {

                    return data.records;
                },
               
            };
           
            $("#table_list_1").setGridParam({ data: data.rows, localReader: reader }).trigger('reloadGrid');
 
             re_records = $("#table_list_1").getGridParam('records');
          
            if(re_records==0||re_records==null){

                if($(".norecords").html() == null){$("#usnameval").val("");
                    $("#table_list_1").parent().append("<div class=\"norecords\">"+domain.language.$t('dev_meiyoufhsj')+"</div>");
                }
                $(".norecords").show();
            }else{

                $(".norecords").hide();
            }

            // console.log(response);
            $("#table_list_1").setGridHeight($(window).height() - 300);
            $("#table_list_1").setGridWidth($(window).width() - 3);
        }
    });
}
$(function(){
    $(".confirm").text(domain.language.$t('queding'));
    $("button").eq(0).click(function(){
       
         cxlist();
    });
    cxlist();
    $("#citySel").click(function(){
        var cityObj = $("#citySel");
        var cityOffset = $("#citySel").offset();
        $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
        $("body").bind("mousedown", onBodyDown);
    });
    $("#company_name").click(function(){
        var cityObj = $("#company_name");
        var cityOffset = $("#company_name").offset();
        $("#menuContenttow").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
    
        $("body").bind("mousedown", onBodyDowntow);
    });
    
$("#user_name").blur(function(){    
    $("#myModal").find("span").eq(0).text("");
    if($("#user_name").val().length==0){
         $("#myModal").find("span").eq(0).text( domain.language.$t('use_yhmbnwk'));
      //  $("#user_name").focus();
       return;
    }
    // if($("#user_name").val().length>12){
    //     $("#myModal").find("span").eq(0).text( domain.language.$t('use_yhmbcg12'));
    //   //  $("#user_name").focus();
    //    return;
    // }
   // if($("#user_name").val().length>0 && $("#user_name").val().length<6){
      //  $("#myModal").find("span").eq(0).text( domain.language.$t('use_yhm6_20'));
      //  $("#user_name").focus();  
     //  return;
   // }


   
    if($("#myModalLabel").text()== domain.language.$t('xinzeng')){
    domain.ajaxUrl({
    method: 'POST',
    url: domain.testUrl+"/Threeinjection/user/queryByUserName",
    data: {"userName":$("#user_name").val()},
    success: function (response) {

     if(response=="\"no\""){
    
                $("#myModal").find("span").eq(0).text(domain.language.$t('use_yhmycz'));
               // $("#user_name").focus();
                return;
            }
    }
    
});
    }
});


$("#mobile").blur(function(){
    $("#myModal").find("span").eq(1).text("");
    if($("#mobile").val().length==0){

        $("#myModal").find("span").eq(1).text( domain.language.$t('use_sjhmbwk'));
       // $("#mobile").focus();
       return;
    }
    
    if(!(/^1[3456789]\d{9}$/.test($("#mobile").val()))){ 
        $("#myModal").find("span").eq(1).text( domain.language.$t('use_sjhmsrcw'));
        // $("#mobile").focus();
        return;
    }
    
   // if($("#mobile").val().substr(0,3)!=138&&$("#mobile").val().substr(0,3)!=189&&$("#mobile").val().substr(0,3)!=139&&$("#mobile").val().substr(0,3)!=158&&$("#mobile").val().substr(0,3)!=188&&$("#mobile").val().substr(0,3)!=157||$("#mobile").val().length!=11){
        
      //  $("#myModal").find("span").eq(1).text("手机号格式不正确");
        //$("#mobile").focus();
       // return;
   // }
   if(mobile!=$("#mobile").val()){
    domain.ajaxUrl({
    method: 'POST',
    url: domain.testUrl+"/Threeinjection/user/queryByUsermobile",
    data: {"mobile":$("#mobile").val()},
    success: function (response) {   
        if(response=="\"no\""){
                $("#myModal").find("span").eq(1).text( domain.language.$t('use_sjhycz'));
               // $("#mobile").focus();  
                 return;
            }
    }
});
   }
});
$("#mail").blur(function(){    
    $("#myModal").find("span").eq(2).text("");
    if($("#mail").val().length>0){
    　var myReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
    　　if(!myReg.test($("#mail").val())){
        $("#myModal").find("span").eq(2).text( domain.language.$t('use_yxsrbzq'));
      //  $("#mail").focus();
       return;
    }
    
}
});
$("#company_name").blur(function(){    
   console.log(123);
   $("#myModal").find("span").eq(3).text("");
    if($("#company_name").val().length==0){
      
        $("#myModal").find("span").eq(3).text( domain.language.$t('use_dwmcbwk'));
      //  $("#company_name").focus();
       return;
    }else{
        $("#myModal").find("span").eq(3).text("");

    }

});
var table="userinfo";
$("#addtj").click(function(){
    var AZ=["user_name","account","user_pwd","company_id","sex","role_id","enter_state","email","mobile"];//字段
    //var valAZ=["user_name","account","user_pwd","company_id","role_id","enter_state","email","mobile"];//字段

    //console.log(findval);
    $("#myModal").find("span").empty();
  //  return;
    //var dataadd={tableName:"userinfo","fieldlist":"user_name','account','user_pwd','company_id','sex','role_id','enter_state','email','mobile'",
  //  "stringvalueA":"'"+$("#user_name").val()+"',"+"'"+$("#user_name").val()+"',"+"'"+hex_md5("123456").toUpperCase()+"',"+"'"+$("#company_id").val()+"',"+"'"+$("#sex").val()+"',"+"'"+$("#jiaose").val()+"',"+"'"+$("#static").val()+"',"+"'"+$("#mail").val()+"',"+"'"+$("#mobile").val()+"'"}
    $("#user_name").blur(); $("#mobile").blur();
   $("#mail").blur(); $("#company_name").blur();
 
  
    //{“tableName”:”表名”, “fielded”:”user_id+”，” value”:”修改条件”}
   
if($("#myModalLabel").text()== domain.language.$t('xinzeng')){
  //var dataadd={tableName:"userinfo",fieldnameA:"user_name",fieldnameB:"account",fieldnameC:"user_pwd",fieldnameD:"company_id",fieldnameE:"role_id",fieldnameF:"enter_state",fieldnameG:"email",fieldnameH:"mobile",
 // stringvalueA:$("#user_name").val(),stringvalueB:$("#user_name").val(),stringvalueC:hex_md5("123456").toUpperCase(),stringvalueD:$("#company_id").val(),stringvalueE:$("#sex").val(),stringvalueF:$("#jiaose").val(),stringvalueL:$("#static").val(),stringvalueG:$("#mail").val(),stringvalueH:$("#mobile").val()}
 var val=[];//数据
 val.push($("#user_name").val());   
val.push($("#user_name").val());   
val.push(hex_md5("123456").toUpperCase()); 
val.push($("#company_id").val());  
val.push($("#sex").val());  
val.push($("#jiaose").val());  
val.push($("#static").val()); 
val.push($("#mail").val()); 
val.push($("#mobile").val()); 

var findval=domain.fieldthis(AZ,val,table);
   //var json=
  // {"tableName":"userinfo", "fielded":""，” valueid”:”修改条件”,”fieldnameA”:”需要修改的字段”，”stringvalueA”:”修改值” }
 setTimeout(function(){  if($("#myModal").find("span").text().length>0){
    return;
}
  $.ajax({
    type: "POST",
    url:domain.testUrl+"/Threeinjection/global/insert",
  // url:domain.testUrl+"/basicmManagementpage/insertCompany",
    data:findval,
    success: function (response) {
      
        response=JSON.parse(response);
        if(response.code=="200"){

            $(".close").click();
             
          
            cxlist();
            swal(domain.language.$t('dev_success'),  domain.language.$t('baocuncg'), "success");
            $(".confirm").text(domain.language.$t('queding'));
        }

    }
    });
},600);
}else{
    var val2=[];//数据
    val2.push($("#user_name").val());   
    val2.push($("#user_name").val());   
    val2.push(hex_md5("123456").toUpperCase()); 
    val2.push($("#company_id").val());  
    val2.push($("#sex").val());  
   // alert($("#jiaose").val());
    val2.push($("#jiaose").val());  
    val2.push($("#static").val()); 
    val2.push($("#mail").val()); 
    val2.push($("#mobile").val()); 
    var findval=domain.fieldupdatethis(AZ,val2,"user_id",$("#user_id").val(),table);
    setTimeout(function(){if($("#myModal").find("span").text().length>0){
        return;
    }
    $.ajax({
    type: "POST",
    url: domain.testUrl+"/Threeinjection/global/update",
    data:findval,
    success: function (response) {
     
        response=JSON.parse(response);
        if(response.code=="200"){
            
            cxlist();
            $(".close").click();
            swal(domain.language.$t('dev_success'),  domain.language.$t('xiugaicg'), "success");
            $(".confirm").text(domain.language.$t('queding'));
        }

    }
    });
},600);
}
});


$("#deleUser").click(function () {
    var userids = "";
    var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");

    //遍历访问这个集合
    $(ids).each(function (index, id) {
        //由id获得对应数据行
        var row = $("#table_list_1").jqGrid('getRowData', id);
        userids += row.user_id + ","

    });
    userids = userids.substring(0, userids.length - 1);
    // console.log(programid);
    if (re_records == 0 || re_records == null) {
        swal( domain.language.$t('tishi'), domain.language.$t('use_zwyh'), "info");
        $(".confirm").text(domain.language.$t('queding'));
        return;
    } else {
        if (userids == "") {

            swal(domain.language.$t('dev_omg'),  domain.language.$t('use_qxzscyh'), "error");
            $(".confirm").text(domain.language.$t('queding'));
            return;
        } else {
            var msg =  domain.language.$t('use_qdscyhm');
            swal({
                title: domain.language.$t('tishi'),
                text: msg,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: domain.language.$t('queding'),
                cancelButtonText: domain.language.$t('quxiao'),
                closeOnConfirm: false,
                closeOnCancel: true
            }, function ss(inputValue) {
                if (inputValue) {
                $.fn.jqLoading({ height: 100, width: 240, text:  domain.language.$t('scztishi')});
                $.ajax({
                    type: 'POST',
                    url: domain.testUrl + "/Threeinjection/user/deleteUserInfo",
                    data: { "userId": userids, sessionid: sessionStorage.getItem("sid") },

                    success: function (response) {
                        response = JSON.parse(response);
                        if (response.code == "200") {

                            
                            cxlist();
                            $.fn.jqLoading("destroy");
                            swal(domain.language.$t('dev_success'),  domain.language.$t('scchenggong'), "success");
                            $(".confirm").text(domain.language.$t('queding'));

                        } else {
                            $.fn.jqLoading("destroy");
                            swal(domain.language.$t('dev_success'),  domain.language.$t('scshibai'), "success");
                            $(".confirm").text(domain.language.$t('queding'));
                        }

                    }
                });
                return true;
            } else {
                userids = "";
                return false;
            }
        });
        }
    }

});

});
 Date.prototype.Format = function(fmt)   
{ 
//author:wangweizhen
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

window.modify=function(i){
    $("#myModal").find("span").empty(); 
    $("#user_name").attr("disabled","disabled");

   $("#myModalLabel").text( domain.language.$t('xiugai'));
 
   $("#update").click();
   i=i-1;
  var jsonval=JSON.parse(json);

  // $("#user_name").val(json[i].email);

$("#user_name").val(jsonval.rows[i].user_name);
mobile=jsonval.rows[i].mobile;
$("#mobile").val(jsonval.rows[i].mobile);
$("#mail").val(jsonval.rows[i].email);

$("#sex").val(jsonval.rows[i].sex);

$("#company_name").val(jsonval.rows[i].coName);
//alert(jsonval.rows[i].companyId);
$("#company_id").val(jsonval.rows[i].companyId);
$("#user_id").val(jsonval.rows[i].user_id);
// $("#jiaose option:first").hide();
if(sessionStorage.getItem("roleId")=="1"){
    $("#jiaose").removeAttr("disabled")
}
// if(jsonval.rows[i].roleId=="1"){
//     $("#jiaose").attr("disabled","disabled");
// }
$("#jiaose").val(jsonval.rows[i].roleId);
$("#static").val(jsonval.rows[i].enter_state);

if(typeof(jsonval.rows[i].sex)=="undefined"){

    $("#sex").val("1");
}
if(typeof(jsonval.rows[i].enter_state)=="undefined"){

    $("#static").val("1");
}

//$("#static").val("1");


 // domain.jsonthis.userinfo=[json.rows[i].user_name];
    
};

